const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin'); // 本都服务
const MiniCssExtractPlugin = require('mini-css-extract-plugin'); // 样式隔离
const { CleanWebpackPlugin }= require('clean-webpack-plugin'); //清除插件
const autoprefixer = require('autoprefixer');  // 自动加前缀，处理兼容性问题
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;  //展示出打包后的各个bundle所依赖的模块
const webpack = require('webpack')

/*
// 测试多入口
const fs = require('fs')
const pageRoot = path.resolve(__dirname, './src/pages')
const entries = fs.readdirSync(pageRoot)
console.log('---pageRoot--')
console.log(pageRoot)
console.log(entries)
*/

module.exports = {
  mode: 'development', // 指定构建模式
  entry: {
      main: './src/index.js'
  }, // 指定构建入口文件
  output: {
    path: path.resolve(__dirname, 'dist'), // 指定构建生成文件所在路径
    filename: 'bundle.[name].js', // 指定构建生成的文件名
  },
  devtool: 'inline-source-map', // 加入devtool配置,做相关的错误映射
  devServer: {
    static: {
      directory: path.join(__dirname, 'dist'),
    },
    compress: true,
    open: true,  // 自动打开浏览器
    hot: true,  // 热加载的配置
    port: 9000,
  },
  module: {
      rules: [
          {
            test: /\.js?/,
            include: [
              path.resolve(__dirname, 'src'),
            ],
            use: {
              loader: 'babel-loader', //指定使用loader
              options: {
                presets: [
                  [
                    '@babel/preset-env',
                    {
                      // 按需加载
                      useBuiltIns: 'usage',
                       // 指定core-js版本
                      corejs: {
                        version: 3
                      },
                      // 指定兼容性做到哪个版本浏览器
                      targets: {
                        chrome: '60',
                        firefox: '60',
                        ie: '8',
                        safari: '10',
                        edge: '17'
                      }
                    }
                  ]
                ]
              }
            }
          },
          // {
          //   test: /\.js?/,
          //   include: [
          //     path.resolve(__dirname, 'src'), // 指定哪些路径下的文件需要经过 loader 处理
          //   ],
          //   use: {
          //     loader: 'babel-loader', // 指定使用的 loader
          //     options: {
          //       presets: ['@babel/preset-env'],
          //     },
          //   },
          // }, 
          {
            test: /\.css$/,   //.css配置
            include: [
                path.resolve(__dirname, 'src'),
            ],
            use: [
                MiniCssExtractPlugin.loader,
                // 'style-loader',
                'css-loader',
                'postcss-loader'
            ]
          },
          {
            test: /\.less$/, //.less配置
            include: [
                path.resolve(__dirname, 'src'),
            ],
            use: [
                MiniCssExtractPlugin.loader,
                // 'style-loader',
                'css-loader',
                // 'postcss-loader',
                'less-loader',
            ]
          },
          {
            test: /\.(eot|woff|otf|svg|ttf|woff2|appcache|mp3|mp4|pdf)(\?|$)/,
            include: path.resolve(__dirname, 'src'),
            use: [
                {
                    loader: 'file-loader',
                    options: {
                        name: "assets/[name].[hash:4].[ext]"
                    }
                }
            ]
          },
          {
            test: /\.(png|jpg|jpeg|gif)$/i, // 配置图片
            include: [
            path.resolve(__dirname, 'src'),  
            ],
            use: [
                {
                    loader: "url-loader",
                    options: {
                        limit: 8192,
                        name: "assets/[name].[hash:4].[ext]"
                    }
                }
            ]
          }
      ]
  },
  plugins: [    
      new webpack.HotModuleReplacementPlugin(),  // 热加载的配置 要加上hot:true
      new webpack.DefinePlugin({
        PRODUCTION: JSON.stringify(true), // const PRODUCTION = true
        VERSION: JSON.stringify('5fa3b9'), // const VERSION = '5fa3b9'
        BROWSER_SUPPORTS_HTML5: true, // const BROWSER_SUPPORTS_HTML5 = 'true'
        TWO: '1+1', // const TWO = 1 + 1,
        CONSTANTS: {
          APP_VERSION: JSON.stringify('1.1.2') // const CONSTANTS = { APP_VERSION: '1.1.2' }
        }
      }),
      new HtmlWebpackPlugin({
        template: 'src/index.html', // 配置文件模板
        inject: true,  // JS文件注入到body结尾，CSS文件注入到head中
        minify: {
          removeComments: true, // 删除模版文件中的注释
        }
      }),
      new MiniCssExtractPlugin({
        filename: '[name].css'
      }),
      new CleanWebpackPlugin(),
      // new BundleAnalyzerPlugin()
  ],
  resolve: {
    extensions: [".js", ".jsx", ".ts", ".tsx", ".less", ".css", ".wasm"],  // 后缀自动补全
    alias: {
      "@": path.resolve(__dirname, 'scr'),   // 路径别名
    },
    modules: ['node_modules'],
  },
  // 使用SplitChunksPlugin不需要安装任何依赖，只需在 webpack.config.js 中的 config对象添加 optimization 属性：
  optimization: {
    namedModules: true,  //配置hot加载，替代webpack4的  new webpack.NamedModulesPlugin(),
    splitChunks: {
      chunks: 'initial',
      automaticNameDelimiter: '.',
      cacheGroups: {
        vendors: {
          test: /[\\/]node_modules[\\/]/,
          priority: 1
        }
      }
    },
    runtimeChunk: {
      name: entrypoint => `manifest.${entrypoint.name}`
    }
  }
}